package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class MyThreadPool{
    // 阻塞队列用来存任务
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    // 此处实现一个固定线程数的线程池
    public MyThreadPool(int n){
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(()->{
                while (true){
                    // 此处需要让线程内部有个 while 循环，不停的取任务
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }
}
public class Demo20 {

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int number = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + number);
                }
            });
        }
    }

}
